# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=libnegf
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.1.3
pkgrel=1
pkgdesc="A general library for Non Equilibrium Green's Functions. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://github.com/libnegf/libnegf'
license=('spdx:LGPL-3.0-or-later')
depends=($([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-openblas")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-omp"
             "${MINGW_PACKAGE_PREFIX}-python-fypp")
source=("https://github.com/libnegf/libnegf/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-install-dll.patch"
        "002-fix-build-on-mingw-w64.patch")
sha256sums=('8d2a41791e459a203db4e4f3a9395804434ce2cd91b1bbb09111cffb032f237e'
            '8666c458cd9815087a59fbe84d4f2d2e599a2a6f7e312d667f86e54d5e56dffd'
            'c95d78ff11dff58051e72e7e351f013d0cc9393e8c48964cf442121222b6bee2')

prepare() {
  cd "${_realname}-${pkgver}"

  patch -Np1 -i "${srcdir}"/001-fix-install-dll.patch
  patch -Np1 -i "${srcdir}"/002-fix-build-on-mingw-w64.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DWITH_MPI=OFF \
      -DWITH_OMP=ON \
      -DBUILD_TESTING=OFF \
      -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python \
      -DFYPP=${MINGW_PREFIX}/bin/fypp \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

check() {
  cmake -S"${_realname}-${pkgver}" -B"build-${MSYSTEM}" -DBUILD_TESTING=ON
  cmake --build "build-${MSYSTEM}"

  PATH="${srcdir}"/build-${MSYSTEM}/src:$PATH \
  ctest --test-dir "build-${MSYSTEM}" --output-on-failure || echo "Tests failed"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE \
    -t "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}
}
